// const mysql = require('mysql2');
const db = require('../config/mysql');
const utils = require('../utils/utils');

// 系统设置模型
class SystemSetting {
    // 获取系统设置（单条，id=1）
    static async getSettings() {
        try {
            const [rows] = await db.query(`
                SELECT 
                    id,
                    sys_name,
                    sys_version,
                    sys_desc,
                    default_house,
                    data_retention_days,
                    system_notic_email,
                    enable_inventory_alerts,
                    enable_generation_plan,
                    enable_analysis_reports,
                    stock_alert_min,
                    stock_alert_max,
                    notification_method,
                    notification_preferences,
                    daily_report_time,
                    week_report_time,
                    pwd_length,
                    pwd_require_num,
                    pwd_require_word,
                    pwd_require_special,
                    login_failur,
                    session_timeout,
                    record_user_log,
                    record_sys_error,
                    update_time
                FROM system_setting 
                WHERE id = 1
            `);

            if (rows.length === 0) {
                return null;
            }

            const settings = rows[0];
            if (settings.update_time) {
                settings.update_time = utils.formatDate(settings.update_time, 'YYYY-MM-DD HH:mm:ss');
            }
            return rows[0];
        } catch (error) {
            console.error('获取系统设置失败:', error);
            throw error;
        }
    }

    // 更新系统设置（id=1）
    static async updateSettings(data) {
        try {
            // 构建动态SQL查询
            const fields = [];
            const values = [];

            // 定义允许更新的字段
            const allowedFields = [
                'sys_name',
                'sys_version',
                'sys_desc',
                'default_house',
                'data_retention_days',
                'system_notic_email',
                'enable_inventory_alerts',
                'enable_generation_plan',
                'enable_analysis_reports',
                'stock_alert_min',
                'stock_alert_max',
                'notification_method',
                'notification_preferences',
                'daily_report_time',
                'week_report_time',
                'pwd_length',
                'pwd_require_num',
                'pwd_require_word',
                'pwd_require_special',
                'login_failur',
                'session_timeout',
                'record_user_log',
                'record_sys_error'
            ];

            // 只处理传入的并且是允许更新的字段
            Object.keys(data).forEach(key => {
                if (allowedFields.includes(key)) {
                    if (key === 'daily_report_time') {
                        // 如果只有时间部分，添加默认日期
                        if (data[key] && !data[key].includes('-')) {
                            const now = new Date();
                            const year = now.getFullYear();
                            const month = String(now.getMonth() + 1).padStart(2, '0');
                            const day = String(now.getDate()).padStart(2, '0');
                            data[key] = `${year}-${month}-${day} ${data[key]}`;
                        }
                    }
                    if (key === 'week_report_time') {
                        // 将星期名称转换为对应的日期
                        const weekMap = {
                            'Sunday': '2023-01-01',
                            'Monday': '2023-01-02',
                            'Tuesday': '2023-01-03',
                            'Wednesday': '2023-01-04',
                            'Thursday': '2023-01-05',
                            'Friday': '2023-01-06',
                            'Saturday': '2023-01-07'
                        };
                        data[key] = weekMap[data[key]] || data[key];
                    }
                    fields.push(`${key} = ?`);
                    values.push(data[key]);
                }
            });

            // 如果没有要更新的字段，则直接返回
            if (fields.length === 0) {
                return { affectedRows: 0 };
            }

            // 添加更新时间
            fields.push('update_time = NOW()');

            // 执行更新操作
            const [result] = await db.query(`
            UPDATE system_setting 
            SET ${fields.join(', ')}
            WHERE id = 1
        `, values);

            return result;
        } catch (error) {
            console.error('更新系统设置失败:', error);
            throw error;
        }
    }
}


module.exports = SystemSetting;